package com.flyduck.common.exception.handler;

import com.flyduck.common.exception.BusinessException;
import com.flyduck.common.exception.CommonExceptionCode;
import com.flyduck.common.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @program: flyduck-platform
 * @description: 统一异常处理
 * @author: flyduck
 * @create: 2021-01-08 21:29
 **/
@Slf4j
@RestControllerAdvice
public class CommonExceptionHandler {

    /**
     * BusinessException 业务异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = BusinessException.class)
    public Result handlerBusinessException(BusinessException e) {
        log.error(e.getMessage(),e);
        //非业务异常，返回信息
        return Result.failure(e.getCode(),e.getMessage());
    }

    /**
     * BindException 参数检验异常处理
     * @Validated SysUserAddReqVO reqVo
     * @param e
     * @return
     */
    @ExceptionHandler(value = BindException.class)
    public Result handlerBindException(BindException e) {
        log.error(e.getMessage(),e);
        //非业务异常，返回信息
        return Result.failure(CommonExceptionCode.ERROR_PARAM.getCode(),e.getAllErrors().get(0).getDefaultMessage());
    }

    /**
     * MethodArgumentNotValidException 参数检验异常处理
     * @RequestBody @Validated SysUserAddReqVO reqVo
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error(e.getMessage(),e);
        //非业务异常，返回信息
        return Result.failure(CommonExceptionCode.ERROR_PARAM.getCode(),e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }

    /**
     * Exception 非业务异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public Result handlerException(Exception e) {
        log.error(e.getMessage(),e);
        //非业务异常，返回     系统错误，请联系管理员!
        return Result.failure(CommonExceptionCode.SYSTEM_ERROR.getCode(),CommonExceptionCode.SYSTEM_ERROR.getMessage());
    }
}
